package com.softer.ztb.common.shiro;

import com.softer.ztb.entity.SysMenu;
import com.softer.ztb.entity.SysRole;
import com.softer.ztb.entity.SysUser;
import com.softer.ztb.mapper.LoginMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * AuthRealm class
 * @author zcz
 * @date 2019/1/16
 */
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private LoginMapper loginMapper;
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("--------------授权开始----------------");
        SysUser user = (SysUser) principals.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissionList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        //查询角色集合
        Set<SysRole> roleSet = loginMapper.findRoleByUsername(user.getUserName());
        if (!CollectionUtils.isEmpty(roleSet)) {
            for(SysRole role : roleSet) {
                roleNameList.add(role.getRoleName());
                //查询权限集合
                Set<SysMenu> permissionSet = loginMapper.findPermissionByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(permissionSet)) {
                    for (SysMenu permission : permissionSet) {
                        permissionList.add(permission.getUrl());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //permissionList.add("edit");// 添加权限
        //permissionList.add("");// 添加权限
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        System.out.println("--------------授权结束----------------");
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token){
        System.out.println("--------------认证开始----------------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        SysUser user = loginMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        System.out.println("--------------认证结束----------------");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassWord(),credentialsSalt, this.getClass().getName());
        return info;
    }

}
